﻿using Omnia.DataModels;
using Omnia.Enums;
using Omnia.Library.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Resources;
using System.Windows.Markup;
using System.IO;
using Microsoft.Phone.Controls;

namespace Omnia.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        #region CommonProperties

        #region Informations
        public Uri BackUri
        {
            get
            {
                PhoneApplicationFrame frame = (PhoneApplicationFrame)Application.Current.RootVisual;
                PhoneApplicationPage page = (PhoneApplicationPage)frame.Content;
                if (page.Tag != null)
                {
                    return page.Tag as Uri;
                }
                return null;
            }
        }
        
        /// <summary>
        /// 总资金
        /// </summary>
        public Double TotalAmount
        {
            get
            {
                try
                {
                    return TotalIncome - TotalExpense;
                }
                catch
                {
                    return 0.00;
                }
            }
        }

        /// <summary>
        /// 总共支出
        /// </summary>
        public Double TotalIncome
        {
            get
            {
                try
                {

                    var collection = Database.CollectionOfTransactions.Where(t => t.Kind == TransactionKindValue.Income);
                    if (collection.Count() > 0)
                    {
                        double value = collection.Sum(t => t.Amount);
                        return value;
                    }
                    else
                    {
                        return 0;
                    }
                }
                catch
                {
                    return 0.00;
                }
            }
        }

        public Double TotalExpense
        {
            get
            {
                try
                {
                    var collection = Database.CollectionOfTransactions.Where(t => t.Kind == TransactionKindValue.Expense);
                    if (collection.Count() > 0)
                    {
                        double value = collection.Sum(t => t.Amount);
                        return value;
                    }
                    else
                    {
                        return 0;
                    }
                }
                catch
                {
                    return 0.00;
                }
            }
        }

        /// <summary>
        /// 当前月份的支出
        /// </summary>
        public TransactionOfMonthInfo CurrentMonthTransactionExpense
        {
            get
            {
                var items = Database.CollectionOfTransactions.Where(t => t.Kind == Enums.TransactionKindValue.Expense && t.Time >= new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1));
                return new TransactionOfMonthInfo(items);
            }
        }

        /// <summary>
        /// 收入在总交易额中占比
        /// </summary>
        public double IncomePercent
        {
            get
            {
                try
                {
                    if (TotalIncome + TotalExpense == 0)
                    {
                        return 0;
                    }
                    return (TotalIncome / (TotalIncome + TotalExpense)) * 100;
                }
                catch
                {
                    return 0.00;
                }
            }
        }

        public int RecentRepaymentCount
        {
            get { return RecentRepaymentCards == null ? 0 : RecentRepaymentCards.Count; }
        }

        public CardInfo RecentRepaymentCard
        {
            get
            {
                return RecentRepaymentCards.FirstOrDefault();
            }
        }
        #endregion

        #region Collections
        
        public IEnumerable<CategoryInfo> CategoriesCollection
        {
            get
            {
                if (!IsDesignMode)
                {
                    if (Database.CollectionOfCategories.Count() == 0)
                    {
                        Database.CollectionOfCategories.InsertOnSubmit(new CategoryInfo() { Name = "其他", Default = true });
                        Database.CollectionOfCategories.InsertOnSubmit(new CategoryInfo() { Name = "其他", Default = true, Kind = TransactionKindValue.Income });
                        Save();
                    }
                }
                return Database.CollectionOfCategories;
            }
        }

        public ObservableCollection<PlaceInfo> StorePlaceCollection
        {
            get
            {
                return new ObservableCollection<PlaceInfo>(Database.CollectionOfPlaces);
            }
        }

        public IEnumerable<CaseInfo> CasesCollection
        {
            get
            {
                return Database.CollectionOfCases.OrderByDescending(c => c.StartDate);
            }
        }

        public IEnumerable<CardInfo> CardsCollection
        {
            get
            {
                IEnumerable<CardInfo> items = Database.CollectionOfCards;
                foreach (CardInfo item in items)
                {
                    if (item.Kind == CardKindValue.Credit)
                    {
                        item.RecentRepay = item.NextRepaymentDate < DateTime.Now.AddDays(GlobalSettings.NotifyDays);
                    }
                }

                return items;
            }
        }

        public ObservableCollection<CardInfo> RecentRepaymentCards
        {
            get
            {
                IEnumerable<CardInfo> creditCards = CardsCollection.Where(c => c.Kind == CardKindValue.Credit);
                return new ObservableCollection<CardInfo>(creditCards.Where(c => c.RecentRepay).OrderBy(c => c.NextRepaymentDate));
            }
        }

        /// <summary>
        /// 分类图标
        /// </summary>
        public IEnumerable<string> CategoryIcons
        {
            get
            {
                StreamResourceInfo rd = Application.GetResourceStream(new Uri("/Omnia.Wallet;Component/Data/PathData.xaml", UriKind.RelativeOrAbsolute));
                ResourceDictionary d = (ResourceDictionary)XamlReader.Load(new StreamReader(rd.Stream).ReadToEnd());

                var coll = d.Where(r => r.Key.ToString().StartsWith("PATH_CATE"));

                foreach (KeyValuePair<object, object> kvp in coll)
                {
                    yield return kvp.Key.ToString();
                }
            }
        }
        #endregion
       
        #endregion

        #region Method
        public double GetMonthlySum(int year, int month, Enums.TransactionKindValue kind)
        {
            IEnumerable<TransactionInfo> transactions = Database.CollectionOfTransactions.Where(t=>t.Kind == kind);
            if (transactions.Count() == 0)
            {
                return 0;
            }
            return transactions.Where(t => t.Year == year && t.Month == month).Sum(t => t.Amount);
        }

        public virtual void NavigateBack()
        {
            if (BackUri != null)
            {
                PhoneApplicationFrame page = (PhoneApplicationFrame)Application.Current.RootVisual;
                page.Navigate(BackUri);
            }
        }
        #endregion
    }
}
